﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Project.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ProjectUpdateApplyRepository : Repository<ProjectUpdateApply, DefaultDbContext>
    {
        private readonly ILogger logger;

        public ProjectUpdateApplyRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<ProjectUpdateApplyRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
        }

        /// <summary>
        /// 本月是否存在修改申请
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public bool ExistsByPrjId(int projectId)
        {
            return DbContext.Exists<ProjectUpdateApply>("project_id=@0 and audit_type>=0  and DATE_FORMAT(create_time,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')", projectId);
        }

        /// <summary>
        /// 是否存在未审核的修改申请
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public bool ExistsByPrjIdNoAudit(int projectId)
        {
            return DbContext.Exists<ProjectUpdateApply>("project_id=@0 and audit_type=0", projectId);
        }

        /// <summary>
        /// 获取修改申请
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ProjectUpdateApply? GetProjectUpdateApply(int projectId)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("project_update_apply")
                .Where("project_id=@0 and audit_type=0 ", projectId)
                .OrderBy("create_time DESC");
            return Get(DbContext.FirstOrDefault<int>(sql));
        }

        /// <summary>
        /// 获取分页记录
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IPagedList<ProjectUpdateApply> GetProjectUpdateApplys(ProjectUpdateApplyQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("project_id")
                .From("project_update_apply");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(industry_prj_num Like @0 or builder_licences Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.ProjectId.HasValue)
                sql.Where("project_id=@0", query.ProjectId.Value);
            if (query.AuditType.HasValue)
                sql.Where("audit_type=@0", query.AuditType.Value);
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }
    }
}